package game_frame

import (
	"errors"
	"fmt"
	"gamesdk/clock"
	"gamesdk/common/log"
	"gamesdk/common/rand"
	"gamesdk/common/redis"
	"gamesdk/global"
	"gamesdk/inter"
	"gamesdk/msg"
	"sync"
	"time"

	"github.com/golang/protobuf/proto"
)

const (
	g_UserStand = 0 //站立
	g_UserDown  = 1 //坐下
	g_UserReady = 2 //用户准备
	g_UserRun   = 3 //游戏中
	g_UserEnd   = 5 //游戏结束
	g_UserLeave = 6 //离开
)
const (
	g_Robot    = true  //是机器人
	g_NoRobot  = false //不是机器人
	g_IsBanker = true  //是庄家
	g_NoBanker = false //不是庄家
)

type User struct {
	client        *Client             //对应服务器
	id            int64               //用户id
	uid           int64               //假ID
	onlineStatus  int64               //在线状态
	token         string              //用户token
	nike          string              //用户昵称
	account       string              //用户账号
	head          string              //头像
	sex           int32               //性别
	sign          string              //签名
	equipmentCode string              //登录设备码	记录玩家每次登录时，登录的设备编码
	loginTime     int                 //登录时间	记录玩家每次登录的时间
	gameId        int64               //游戏ID
	roomId        int64               //房间id
	loginGame     string              //登录游戏	记录本次登录 是进入大厅或者子游戏
	balance       int64               //登录时携带金币	记录玩家登录时用户携带金币数额
	drawAmount    int64               //抽水金额
	endCards      string              //结算牌
	profitAmount  int64               //盈利金额
	platformId    int64               //登录平台ID	记录登录的平台ID号
	betsAmount    int64               //总下注
	status        int                 //状态
	isRobot       bool                //是否是机器人
	tableId       int                 //桌子
	chairId       int                 //所在椅子
	prob          int32               //点控级别
	chip          int64               //分
	city          string              //城市
	ip            string              //ip地址
	banker        bool                //是否是庄家
	room          *Room               //房间
	clock         *clock.Clock        //定时器
	interRobot    inter.RobotInter    //机器人
	data          string              //用户消息
	level         int                 //等级
	c2sCmdGameEnd *msg.C2SCmdGameEnds //战绩
	timeCallBack  chan func()
	exit          chan bool
	exitOut       bool
	lock          sync.RWMutex
}

func NewRobot(client *Client, id, uid int64, token string, level int, nike, account string, head string, sex int32, sign string, equipmentCode string, loginTime int, gameId int64, roomId int64, loginGame string, balance int64, platformId int64, city string, ip string, room *Room) *User {
	defer log.Trace()()

	user := &User{
		client:        client,                  //通讯管道
		id:            id,                      //用户id
		uid:           uid,                     //假id
		token:         token,                   //用户token
		nike:          nike,                    //用户昵称
		account:       account,                 //用户账号
		head:          head,                    //头像
		sex:           sex,                     //性别
		sign:          sign,                    //签名
		equipmentCode: equipmentCode,           //登录设备码	记录玩家每次登录时，登录的设备编码
		loginTime:     loginTime,               //登录时间	记录玩家每次登录的时间
		gameId:        gameId,                  //游戏ID
		roomId:        roomId,                  //房间id
		loginGame:     loginGame,               //登录游戏	记录本次登录 是进入大厅或者子游戏
		balance:       balance,                 //登录时携带金币	记录玩家登录时用户携带金币数额
		platformId:    platformId,              //登录平台ID	记录登录的平台ID号
		status:        g_UserStand,             //站立
		isRobot:       g_Robot,                 //不是机器人
		tableId:       -1,                      //桌子
		chairId:       -1,                      //所在椅子
		c2sCmdGameEnd: new(msg.C2SCmdGameEnds), //战绩
		ip:            ip,
		clock:         clock.CreateClock(),
		room:          room,
		interRobot:    nil,
		prob:          0,
		data:          "",
		drawAmount:    0,
		endCards:      "",
		profitAmount:  0,
		chip:          0,
		betsAmount:    0,
		city:          city,
		level:         level,
		timeCallBack:  make(chan func(), 100),
		exit:          make(chan bool),
		banker:        g_NoBanker,
		exitOut:       false,
	}
	user.c2sCmdGameEnd.GameEnds = make([]*msg.C2SCmdGameEnd, 0)
	user.robotTimer()
	user.client.AddUser(user)
	return user
}

func (this *User) robotTimer() {
	go func() {
		for {
			select {
			case fn := <-this.timeCallBack:
				if this.exitOut {
					break
				}
				if fn == nil {
					log.Warn("fn is nil")
				} else {
					this.TimerMsg(fn)
				}
			case <-this.exit:
				this.exitOut = true
				//close(this.exit)
				this.exit = nil
				//close(this.timeCallBack)
				this.timeCallBack = nil
				this.clock.Close()
				log.Info("机器人退出 %d", this.id)
				return
			}
		}
	}()
}

//定时器消息
func (this *User) TimerMsg(fn func()) {
	log.Listen(fn, func(f interface{}) {
		f.(func())()
	}, fmt.Sprintf("定时 %s id:%d", log.GetFunctionName(fn), this.id))
}

func NewUser(client *Client, id, uid int64, token string, level int, nike, account string, head string, sex int32, sign string, equipmentCode string, loginTime int, gameId int64, roomId int64, loginGame string, balance int64, platformId int64, prob int32, city string, ip string, room *Room) *User {
	defer log.Trace()()
	var data string
	var err error
	data, err = redis.Get(fmt.Sprintf("game-%d-%d-%d", gameId, roomId, id))
	if err != nil {
		log.Warn(err.Error())
		data = ""
	}
	user := &User{
		client:        client,                  //通讯管道
		id:            id,                      //用户id
		uid:           uid,                     //假id
		token:         token,                   //用户token
		nike:          nike,                    //用户昵称
		account:       account,                 //用户账号
		head:          head,                    //头像
		sex:           sex,                     //性别
		sign:          sign,                    //签名
		equipmentCode: equipmentCode,           //登录设备码	记录玩家每次登录时，登录的设备编码
		loginTime:     loginTime,               //登录时间	记录玩家每次登录的时间
		gameId:        gameId,                  //游戏ID
		roomId:        roomId,                  //房间id
		loginGame:     loginGame,               //登录游戏	记录本次登录 是进入大厅或者子游戏
		balance:       balance,                 //登录时携带金币	记录玩家登录时用户携带金币数额
		platformId:    platformId,              //登录平台ID	记录登录的平台ID号
		status:        g_UserStand,             //站立
		isRobot:       g_NoRobot,               //不是机器人
		tableId:       -1,                      //桌子
		chairId:       -1,                      //所在椅子
		c2sCmdGameEnd: new(msg.C2SCmdGameEnds), //战绩
		ip:            ip,
		clock:         nil,
		room:          room,
		level:         level,
		interRobot:    nil,
		prob:          prob,
		data:          data,
		drawAmount:    0,
		betsAmount:    0,
		endCards:      "",
		profitAmount:  0,
		chip:          0,
		timeCallBack:  nil,
		exit:          nil,
		city:          city,
		banker:        g_NoBanker,
	}
	user.c2sCmdGameEnd.GameEnds = make([]*msg.C2SCmdGameEnd, 0)
	user.client.AddUser(user)
	return user
}

func (this *User) GetSex() int32 {
	return this.sex
}

func (this *User) GetCity() string {
	return this.city
}

func (this *User) EXit() {
	this.client.DelUser(this)
	if this.isRobot {
		if this.exit != nil {
			this.exit <- true
		}

	}
}

//GetUID 获取UID
func (this *User) GetUID() int64 {
	return this.uid
}

//WriteLogs 发送日志
func (this *User) SendLogs(gameNum string, records []*msg.GameLog) {
	//上传日志
	c2sGameLog := &msg.C2SGameLog{
		MatchId:    gameNum,
		GameId:     global.G_Config.GameId,
		GameLogs:   records,
		PlatformId: this.platformId,
	}
	buff1, err := proto.Marshal(c2sGameLog)
	if err == nil {
		this.room.funcWrietLogs(int32(msg.CMDKIND_GAMELOG), 0, buff1)
		log.Test("用户发生日志成功%v", c2sGameLog)
	} else {
		log.Error(err.Error())
	}
}

//获取用户ip
func (this *User) GetIp() string {
	defer log.Trace()()
	return this.ip
}

//上庄 成为庄家
func (this *User) UpBanker() {
	defer log.Trace()()
	this.banker = g_IsBanker
}

//下庄 失去庄家
func (this *User) DownBanker() {
	defer log.Trace()()
	this.banker = g_NoBanker
}

//创建打码量
func (this *User) SendChip(chip int64) {
	defer log.Trace()()
	log.Info("发送打码量%d 打码量 %d开始", this.id, chip)
	if this.isRobot || chip == 0 {
		return
	}

	c2sChipCreat := &msg.C2SChipCreat{
		UserId:     this.id,
		PlatformId: this.platformId,
		Amount:     chip,
		Note:       "",
	}
	data, err := proto.Marshal(c2sChipCreat)
	if err != nil {
		log.Warn(err.Error())
		return
	}
	log.Info("发送打码量%d 打码量 %d结束", this.id, chip)
	this.funcSendMsg(int32(msg.CMDKIND_CHIPCREAT), this.id, data)
	this.chip = 0
}

/*
发送战绩
gameNum 局号
profitAmount 盈利
betsAmount 总下注
drawAmount 总抽水
outputAmount 总产出
endCards 结算牌
*/
func (this *User) SendRecord(gameNum string, profitAmount, betsAmount, drawAmount, outputAmount int64, endCards string) {
	if profitAmount != 0 || endCards != "" || drawAmount != 0 || betsAmount != 0 || outputAmount != 0 {
		c2sCmdGameEnd := &msg.C2SCmdGameEnd{
			UserId:       this.id,
			GameId:       this.gameId,
			MatchId:      gameNum,
			RoomId:       this.roomId,
			TableId:      int32(this.tableId),
			ChairId:      int32(this.chairId),
			ProfitAmount: profitAmount,
			BetsAmount:   betsAmount,
			EndCards:     endCards,
			DrawAmount:   drawAmount,
			OutputAmount: outputAmount,
			Role:         1,
			PlatformId:   this.platformId,
		}
		if this.isRobot {
			c2sCmdGameEnd.Role = 2
		}
		this.c2sCmdGameEnd.GameEnds = append(this.c2sCmdGameEnd.GameEnds, c2sCmdGameEnd)
		buff, err := proto.Marshal(this.c2sCmdGameEnd)
		if err == nil {
			this.room.funcSendMsg(int32(msg.CMDKIND_END), 0, buff)
			log.Info("发送战绩 %v", this.c2sCmdGameEnd)
		} else {
			log.Error(err.Error())
		}
	}
	this.profitAmount = 0
	this.endCards = ""
	this.drawAmount = 0
	this.betsAmount = 0

	//清空上一轮切片
	this.c2sCmdGameEnd.GameEnds = make([]*msg.C2SCmdGameEnd, 0)
}

//生成局号
func (this *User) GetRoomNum() string {
	id := time.Now().Nanosecond()
	return fmt.Sprintf("%d%d%d%s", id, this.platformId, global.G_Config.GameId, rand.Rand4())
}

//获取点控
func (this *User) GetProb() int32 {
	defer log.Trace()()
	this.lock.RLock()
	defer this.lock.RUnlock()
	//log.Info("获取用户%d点控%d", this.id, this.prob)
	return this.prob
}

func (this *User) SetProb(prob int32) {
	defer log.Trace()()
	this.lock.Lock()
	defer this.lock.Unlock()
	this.prob = prob
	log.Info("设置用户%d点控%d", this.id, prob)
}

//判断用户是否为机器人
func (this *User) IsRobot() bool {
	defer log.Trace()()
	return this.isRobot
}

//获取用户当前状态
func (this *User) GetStatus() int {
	defer log.Trace()()
	return this.status
}
func (this *User) SetStatus(status int) {
	defer log.Trace()()
	this.status = status
}

//获取用户昵称
func (this *User) GetNike() string {
	defer log.Trace()()
	return this.nike
}

//获取用户头像
func (this *User) GetHead() string {
	defer log.Trace()()
	return this.head
}

//获取用户积分
func (this *User) GetScore() int64 {
	defer log.Trace()()
	return this.balance
}

//获取用户积分
func (this *User) GetRoomID() int64 {
	defer log.Trace()()
	return this.roomId
}

//获取流水号
func (this *User) GetGlobalNum() string {
	defer log.Trace()()
	return fmt.Sprintf("%d%d%d%d", time.Now().UnixNano(), this.id, this.roomId, this.platformId)
}

//设置用户积分 操作类型 1:投注 2:结算
func (this *User) SetScore(gameNum string, score int64, tax int64) (int64, error) {
	defer log.Trace()()
	log.Debug("用户%d输赢情况 输赢:%d 剩余钱%d,抽水比例%d  局号%s", this.id, score, this.balance, tax, gameNum)
	if gameNum == "" {
		log.Error("局id为空")
		return -1, errors.New("局id为空")
	}
	before := this.balance
	taxMoney := int64(0)
	money := score
	profiltAmount := score
	if score > 0 {
		if profiltAmount > 0 {
			taxMoney = ((score) * tax) / 10000
			y := ((score) * tax) % 10000
			if y > 0 {
				taxMoney = taxMoney + 1
			}
		} else {
			profiltAmount = 0
		}
	}
	score = score - taxMoney
	after := before + score
	num := this.GetGlobalNum()
	//通知网管上下分
	data := &msg.UserUpAndDown{
		//用户ID
		Userid: this.id,
		//用户上下分的钱（没有算税）
		ChangeMoney: money,
		//扣税的钱
		TaxMoney: taxMoney,
		//流水号
		Num: num,
		//游戏局号
		GameNum: gameNum,
		//规则
		Role: 1,
		//业主id
		PlatformId: this.platformId,
		//要扣税的钱
		ProfiltAmount: profiltAmount,
	}
	if this.isRobot {
		data.Role = 2
	}
	this.funcUserUpAndDown(data)

	// if global.G_Path {
	// 	err := record.SendGameChangeInfoLog(this.id, this.nike, this.platformId, this.gameId, this.roomId, gameNum, before, score, after, money, tax, int64(taxMoney), this.isRobot)
	// 	if err != nil {
	// 		log.Error(err.Error())
	// 		return -1, err
	// 	}
	// }
	this.balance = after
	log.Debug("用户%d输赢情况 税收%d 输赢:%d 剩余钱%d,抽水比例%d 局号%s", this.id, taxMoney, score, after, tax, gameNum)
	return score, nil
}

//发送上下分消息
func (this *User) funcUserUpAndDown(data *msg.UserUpAndDown) {
	defer log.Trace()()
	//直接发送
	c2sUserUpAndDown := &msg.C2SUserUpAndDown{Lists: []*msg.UserUpAndDown{data}}
	buffer, err := proto.Marshal(c2sUserUpAndDown)
	if err != nil {
		log.Error(err.Error())
	} else {
		this.funcSendMsg(int32(msg.CMDKIND_USERUPANDDOWN), 0, buffer)
		log.Debug("向%s发送上下分%v", this.client.id, c2sUserUpAndDown)
	}
}

//设置桌子
func (this *User) SetTableId(id int) {
	defer log.Trace()()
	this.tableId = id
}

//获取桌子ID
func (this *User) GetTableId() int {
	defer log.Trace()()
	return this.tableId
}

//设置用户数据
func (this *User) SetTableData(data string) {
	defer log.Trace()()
	go func() {
		if !this.isRobot {
			this.data = data
			redis.Set(fmt.Sprintf("game-%d-%d-%d", this.gameId, this.roomId, this.id), data)
		}
	}()
}

//删除用户数据
func (this *User) DelTableData() {
	defer log.Trace()()
	if !this.isRobot {
		redis.DEL(fmt.Sprintf("game-%d-%d-%d", this.gameId, this.roomId, this.id))
		this.data = ""
	}
}

//获取用户数据
func (this *User) GetTableData() string {
	defer log.Trace()()
	return this.data
}

//删除桌子ID
func (this *User) DelTableId() {
	defer log.Trace()()
	this.tableId = -1
}

//设置椅子ID
func (this *User) SetChairId(id int) {
	defer log.Trace()()
	this.chairId = id
}

//获取椅子ID
func (this *User) GetChairId() int {
	defer log.Trace()()
	return this.chairId
}

//删除椅子ID
func (this *User) DelChairId() {
	defer log.Trace()()
	this.chairId = -1
}

//获取用户ID
func (this *User) GetId() int64 {
	defer log.Trace()()
	return this.id
}

//用户坐下
func (this *User) SetDown() {
	defer log.Trace()()
	this.status = g_UserDown
	this.onlineStatus = g_UserDown
}

//用户准备
func (this *User) Ready() {
	defer log.Trace()()
	this.status = g_UserReady
}

//用户开始游戏
func (this *User) GameRun(gameNum string) {
	defer log.Trace()()
	this.status = g_UserRun
	//this.room.funcSendMsg(int32(msg.CMDKIND_USERSTART), this.GetId(), []byte(gameNum))
	log.UserInfoLog(this.GetId(), "开始游戏 gameNum:%s,roomId:%d", gameNum, this.roomId)
}

//用户游戏结束
func (this *User) GameEnd(gameNum string) {
	defer log.Trace()()
	this.status = g_UserEnd
	//this.room.funcSendMsg(int32(msg.CMDKIND_USEREND), this.GetId(), []byte(gameNum))
	log.UserInfoLog(this.GetId(), "结束游戏 gameNum:%s,roomId:%d", gameNum, this.roomId)
}

//用户离开
func (this *User) Leave() {
	defer log.Trace()()
	this.status = g_UserStand
	this.chairId = -1
	this.tableId = -1
}

/*
*用户发送消息
 */
func (this *User) SendMsg(subCmd int32, pb proto.Message) error {
	defer log.Trace()()
	if this.onlineStatus == g_UserLeave {
		return errors.New("用户已经离开")
	}
	buff, err := proto.Marshal(pb)
	if err != nil {
		log.Warn(err.Error())
		return err
	}
	if this.isRobot {
		//log.Debug("机器人给客户端发送消息 %d", this.id)
		go this.OnSendMsgToClient(int32(msg.MSGTYPE_SUBCMD), subCmd, buff)
	} else {
		frameMsg := &msg.FrameMsg{MainCmd: int32(msg.MSGTYPE_SUBCMD), SubCmd: subCmd, Buff: buff, Time: time.Now().Unix()}
		data, err := proto.Marshal(frameMsg)
		if err != nil {
			log.Warn(err.Error())
			return err
		}
		//log.Info("%d发送逻辑消息%d:%d", this.id, frameMsg.MainCmd, frameMsg.SubCmd)
		log.Listen(this.funcSendMsg, func(f interface{}) {
			f.(func(int32, int64, []byte))(int32(msg.CMDKIND_LOGIC), this.id, data)
		}, "")
	}
	return nil
}

func (this *User) funcSendMsg(cmd int32, userId int64, body []byte) {
	//log.Debug("%v", this)
	sendMsg := &msg.C2SNoticeMsg{Cmd: cmd, UserId: userId, Body: body, Token: this.room.token, MsgId: time.Now().UnixNano()}
	if this.client != nil {
		this.client.funcWrite(sendMsg)
	}
}

/*
*框架内部使用发送框架消息
 */
func (this *User) sendMsgF(subCmd int32, buff []byte) error {
	defer log.Trace()()
	if this.onlineStatus == g_UserLeave {
		return nil
	}
	if this.isRobot {
		//log.Debug("机器人给客户端发送消息")
		go this.OnSendMsgToClient(int32(msg.MSGTYPE_MAINCMD), subCmd, buff)
	} else {
		frameMsg := &msg.FrameMsg{MainCmd: int32(msg.MSGTYPE_MAINCMD), SubCmd: subCmd, Buff: buff, Time: time.Now().Unix()}
		data, err := proto.Marshal(frameMsg)
		if err != nil {
			log.Warn(err.Error())
			return err
		}
		this.funcSendMsg(int32(msg.CMDKIND_LOGIC), this.id, data)
		// log.Listen(this.room.funcSendMsg, func(f interface{}) {
		// 	f.(func(int32, int64, []byte))(int32(msg.CMDKIND_LOGIC), this.id, data)
		// }, "")
	}
	return nil
}

//机器人逻辑绑定
func (this *User) BindRobot(interRobot inter.RobotInter) inter.AIUserInter {
	defer log.Trace()()
	this.interRobot = interRobot
	return this
}

//////////////////////////////////////////////////AI接口

//接收到服务器发给机器人到消息-发送到机器人逻辑
func (this *User) OnSendMsgToClient(mainCmd int32, subCmd int32, buff []byte) {
	if mainCmd == int32(msg.MSGTYPE_MAINCMD) {
		if subCmd == int32(msg.MSGKIND_MATCH) {
			s2cEnter := &msg.S2CEnter{}
			err := proto.Unmarshal(buff, s2cEnter)
			if err != nil {
				log.Error(err.Error())
			} else {
				//log.Warn("收到匹配成功消息 enterid %d:%d", s2cEnter.UserId, this.id)
				if s2cEnter.UserId == this.id {
					this.sendMsgToServerF(int32(msg.MSGKIND_READY), nil)
				} else {
					//log.Debug("有人进入房间 user id %d", s2cEnter.UserId)
				}
			}
			return
		}
		if subCmd == int32(msg.MSGKIND_READY) {
			//用户准备
			ready := &msg.S2CReady{}
			err := proto.Unmarshal(buff, ready)
			if err != nil {
				log.Error(err.Error())
			} else {
				if ready.UserId == this.id {
					//log.Debug("机器人准备")
				} else {
					//log.Debug("有人准备 user id %d", ready.UserId)
				}
			}
			return
		}
		if subCmd == int32(msg.MSGKIND_LEAVE) {
			leave := &msg.S2CLeave{}
			err := proto.Unmarshal(buff, leave)
			if err != nil {
				log.Error(err.Error())
			} else {
				if leave.UserId == this.id {
					//user.Exit()
					//log.Debug("机器人离开了")
				} else {
					//log.Debug("有人离开了 user id %d", leave.UserId)
				}
			}
			return
		}
	}
	if mainCmd == int32(msg.MSGTYPE_SUBCMD) {
		if this.interRobot != nil {
			log.Listen(this.interRobot.OnGameMessage, func(f interface{}) {
				f.(func(int32, []byte))(subCmd, buff)
			}, "")
			//this.interRobot.OnGameMessage(subCmd, buff)
		}
	}

}

//发生逻辑消息
func (this *User) SendMsgToServer(subCmd int32, pb proto.Message) error {
	defer log.Trace()()
	if this.onlineStatus == g_UserLeave {
		return nil
	}
	buff, pberr := proto.Marshal(pb)
	if pberr != nil {
		log.Warn(pberr.Error())
		return pberr
	}
	if this.isRobot {
		//如果是机器人直接发送
		frameMsg := &msg.FrameMsg{MainCmd: int32(msg.MSGTYPE_SUBCMD), SubCmd: subCmd, Buff: buff, Time: time.Now().Unix()}
		data, err := proto.Marshal(frameMsg)
		if err != nil {
			log.Warn(err.Error())
			return err
		}
		body := &msg.S2CNoticeMsg{Cmd: int32(msg.CMDKIND_LOGIC), UserId: this.id, Body: data}
		go this.room.funcRobotMsg(&AcceptMsg{this.client, body})
		return nil
	}
	return errors.New("no robot")
}

//发送框架消息
func (this *User) sendMsgToServerF(subCmd int32, buff []byte) error {
	defer log.Trace()()
	if this.onlineStatus == g_UserLeave {
		return nil
	}
	if this.isRobot {
		//如果是机器人直接发送
		frameMsg := &msg.FrameMsg{MainCmd: int32(msg.MSGTYPE_MAINCMD), SubCmd: subCmd, Buff: buff, Time: time.Now().Unix()}
		data, err := proto.Marshal(frameMsg)
		if err != nil {
			log.Warn(err.Error())
			return err
		}
		body := &msg.S2CNoticeMsg{Cmd: int32(msg.CMDKIND_LOGIC), UserId: this.id, Body: data}
		go this.room.funcRobotMsg(&AcceptMsg{this.client, body})
		return nil
	}
	return errors.New("no robot")
}

//机器人离开房间
func (this *User) LeaveRoom() error {
	defer log.Trace()()
	if this.IsRobot() {
		return this.sendMsgToServerF(int32(msg.MSGKIND_LEAVE), nil)
	} else {
		return errors.New("no robot")
	}
}

//统一定时回调
func (this *User) callback(inter interface{}) {
	defer log.Trace()()
	if this.exitOut {
		return
	}
	if this.timeCallBack != nil {
		this.timeCallBack <- inter.(func())
	}
}

//添加定时器
func (this *User) AddTimer(actionInterval time.Duration, jobFunc func()) (job *clock.Job, ok bool) {
	defer log.Trace()()
	if !this.isRobot {
		return nil, false
	}
	//添加定时
	return this.clock.AddClock(actionInterval*time.Millisecond, 1, this.callback, jobFunc)

	//return this.clock.AddJobWithInterval(actionInterval*time.Millisecond, jobFunc)
}

//添加重复定时器
func (this *User) AddTimerRepeat(interval time.Duration, actionMax uint64, jobFunc func()) (jobScheduled *clock.Job, inserted bool) {
	defer log.Trace()()
	if !this.isRobot {
		return nil, false
	}
	//return this.clock.AddJobRepeat(interval*time.Millisecond, actionMax, jobFunc)
	return this.clock.AddClock(interval*time.Millisecond, int(actionMax), this.callback, jobFunc)
}

//创建跑马灯
func (this *User) CreateMarquee(content string) error {
	defer log.Trace()()
	c2sMarquee := &msg.C2SMarquee{GameId: global.G_Config.GameId, PlatformId: this.platformId, Content: content}
	broadcastsData, err := proto.Marshal(c2sMarquee)
	if err != nil {
		log.Warn(err.Error())
		return err
	}
	this.funcSendMsg(int32(msg.CMDKIND_MARQUEE), 0, broadcastsData)
	// log.Listen(this.room.funcSendMsg, func(f interface{}) {
	// 	f.(func(int32, int64, []byte))(int32(msg.CMDKIND_MARQUEE), 0, broadcastsData)
	// }, "")
	return nil
}
